package com.example.purchase.network;

import com.example.purchase.network.service.HttpService;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitClient {

    //配置成单例工厂模式
    private static volatile RetrofitClient mInstance;
    //配置基本路由
    private static final String BASE_URL = "http://47.107.231.209:20000/";
    //设置成员属性 私有化
    private Retrofit retrofit;
    private HttpService service;

    //DLC单例双重加锁校验
    public static RetrofitClient getInstance(){
        if (mInstance == null){
            synchronized (RetrofitClient.class){
                if (mInstance == null){
                    mInstance = new RetrofitClient();
                }
            }
        }
        return mInstance;
    }

    //传入接口类，进行动态代理
    public <T> T getService(Class<T> cls){
        return getRetrofit().create(cls);
    }

    //返回Retrofit对象
    private synchronized Retrofit getRetrofit() {
        if (retrofit == null){
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }

}